<?php

/**

 * 注册登录接口文件

 * @author maniac

 */

namespace app\api\controller\v1;
use app\common\model\MemberQy;
use app\common\model\WechatUsers;
use app\facade\Aes as AesFacade;
use app\facade\Verify AS VerifyFacade;
use app\facade\Members AS MembersFacade;
use app\facade\Options AS OptionsFacade;
use app\facade\Wechat AS WechatFacade;
use app\common\model\Options AS OptionsModel;

use think\facade\Env;
use \weixin\jssdk;
use weixin\WXBizDataCrypt;

class Login extends Base
{

    /**
    * 注册
    */
    public function register()
    {
    
    	$post = input('post.');
    	
    	if (empty($post['mobile'])) {
    		 
    		return j(1, '请输入注册手机号');
    	
    	}
    	
    	if (empty($post['verify']) && $post['verify'] != '1234') {
    		 
    		return j(1, '请输入验证码');
    		 
    	}
    	
    	if (empty($post['password'])) {
    		 
    		return j(1, '请输入密码');
    	
    	}
    	
    	try {
    
    		$info = MembersFacade::add($post);
    
    		return j(0, '注册成功', $info);
    
    	} catch (\Exception $e) {
    
    		return j(1, $e->getMessage());
    
    	}
    
    }
    /**
     * 登录
     */
    public function login()
    {
    	$post = input('post.');
    	if (empty($post['mobile'])) {
    		return j(1, '请输入注册手机号');
    	}
    	if (empty($post['password'])) {
    		return j(1, '请输入密码');
    	}
        try {
            $result = MembersFacade::login($post);
            return j(0, '登录成功', $result);

        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    /**
     * 找回密码
     */
    public function password(){
    	$post = input('post.');
    	 
    	if (empty($post['mobile'])) {
    		 
    		return j(1, '请输入注册手机号');
    		 
    	}
    	if (empty($post['verify'])) {
    		 
    		return j(1, '请输入验证码');
    		 
    	}
    	if (empty($post['password'])) {
    		 
    		return j(1, '请输入新密码');
    		 
    	}
        try {

            $info = MembersFacade::password($post);

            return j(0, '修改密码成功');

        } catch (\Exception $e) {

            return j(1, $e->getMessage());
        }
    }
    /**
     * 获取用户条款和隐私协议
     */
    public function clause(){


    	$type = input('post.type/d', 0);
    	
    	$options = unserialize(OptionsFacade::option('shop_info'));
    	
    	if ($type == 1) {
    		
    		$info['title'] = isset($options['clause_title']) ? $options['clause_title'] : '';
    		 
    		$info['content'] = isset($options['clause_content']) ? $options['clause_content'] : '';
    	}else{
    		
    		$info['title'] = isset($options['clause_shop_title']) ? $options['clause_shop_title'] : '';
    		 
    		$info['content'] = isset($options['clause_shop_content']) ? $options['clause_shop_content'] : '';
    	}
    	
    	
    	
        try {
        	
            return j(0, '获取信息成功', $info);

        } catch (\Exception $e) {

            return j(1, $e->getMessage());
        }
    }
	/**
	 * 第三方登录(微信QQ)APP
	 *  * @author 董伟
	 */
	public function other_login()
	{
		$type = input('post.type');//1微信 2是QQ
		$data = json_decode(input('post.data'),true);

		if(isset($data["auth_code"]) && !empty($data["auth_code"])){

			$user_info = AlipayFacade::getUser($data["auth_code"]);
			$where = [
				'openid' => $data['user_id'],//这个是支付宝给返的参数类似于openid
			];
			$info = WechatUsers::field(true)->where($where)->find();
		}else{
			$where = [
				'unionid' => $data['unionid'],
			];
			$info = WechatUsers::field(true)->where($where)->find();
		}
		if (empty($info)){
			$data['type']=$type;
			$res = WechatFacade::add($data);
			$userToken=$res['userToken'];
		}else{
			if($info['uid'] > 0){
				$where = [
					'id' => $info['uid'],
				];
				$member = MembersModel::field('id,mobile,password')->where($where)->find();
				$encrypt = [
					'id'      => $member['id'],
					'mobile' => $member['mobile'],
					'password'  => $member['password'],
				];
				$userToken = AesFacade::encrypt(http_build_query($encrypt));
			}else{
				$userToken = $info['unionid'];
			}
		}
		$result = [];
		$result['type'] = $type;
		$result['model_type'] = $type;
		$result['userToken'] = $userToken;
		return j(0, '登录成功', $result);
	}
	/*
	 * 支付宝登录授权
	 *  * @author 董伟
	*/
	public function alipay_login(){
		$user_info = AlipayFacade::alipay_login();
		return j(0, '获取信息成功', $user_info);
	}
	/*
	 * 公众号授权
	 * @author 董伟
	 * */
	public function weixin(){
		$code=input('code','');
		$app_id=config('site.app_id');
		$secret=config('site.app_secret');
		$parent_id=input('parent_id',0);
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$secret}&code=".$code."&grant_type=authorization_code";
		$result = file_get_contents($url);

		$data = json_decode($result,true);
        $options = unserialize(OptionsFacade::option('app_info'));
		if(!empty($data['access_token']) && !empty($data['openid'])) {
            if($options['is_wx_subscribe']) {
//                $Wx = new JSSDK(config('site.app_id'),config('site.app_secret'));
                $accessToken = WechatFacade::getAccessToken();
                $user_info = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" .$accessToken . "&openid=" . $data['openid'] . "&lang=zh_CN";
                $wxuinfo = file_get_contents($user_info);
                $info = json_decode($wxuinfo,true);
                if($info['subscribe'] == 0){
                    return j(333, '请先关注公众号', $options['is_wx_url']);
                }
                $info['openid'] = $data['openid'];
                $info['unionid'] = isset($data['unionid'])?$data['unionid']:'';
                $info['parent_id']=isset($parent_id)?$parent_id:0;
                $info['type']=1;
            }else{
                $urls = "https://api.weixin.qq.com/sns/userinfo?access_token=" .$data['access_token'] . "&openid=" . $data['openid'] . "&lang=zh_CN";
                $wxuinfo = file_get_contents($urls);
                $info = json_decode($wxuinfo,true);
                $info['openid'] = $data['openid'];
                $info['unionid'] = isset($data['unionid'])?$data['unionid']:'';
                $info['parent_id']=isset($parent_id)?$parent_id:0;
                $info['type']=1;
            }
			$result = WechatFacade::add($info);
			if ($result) {
				return j(0, '登录成功', $result);
			}
			return j(1, '登录失败');
		}
		return j(1, '授权失败');
	}
	/*
	 * 微信小程序授权
	 * @author 董伟
	 * */
    public function weixinGetOpenId(){
        $rootPath = str_replace('\\', '/', Env::get('root_path'));
        require $rootPath.'extend/weixin/wxBizDataCrypt.php';

        $data=array();
        $code   =   input('code');
        $encryptedData   =   input('encryptedData');
        $iv   =   input('iv');
        $parent_id   =   input('parent_id');
        if(empty($code)){
            return j(1, '参数错误');
        }

        $app_id=config('site.app_id');
        $secret=config('site.app_secret');

        $url="https://api.weixin.qq.com/sns/jscode2session?appId=".$app_id."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        $apiData=file_get_contents($url);
        $apiData=json_decode($apiData,true);
        if(!isset($apiData['errcode'])){
            $sessionKey = $apiData["session_key"];
            $userifo = new WXBizDataCrypt($app_id, $sessionKey);

            $data['parent_id'] = $parent_id;
            $errCode = $userifo->decryptData($encryptedData, $iv, $data );

            if ($errCode == 0) {
                $data=json_decode($data,true);
                $result = WechatFacade::add($data);
                if ($result) {
                    return j(0, '登录成功', $result);
                }
                return j(1, '登录失败');
            } else {
                return j(1,"解密失败", $errCode);
            }
        }else{
            return j(1,"获取SESSION失败",$apiData);
        }
    }
    //企业微信登录
    public function pyWechatLogin(){
        $code = input('code');
        if(empty($code)){
            return j(1, '参数错误');
        }
        $access_token = WechatFacade::getPyAccessToken(false);
        $url="https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=".$access_token."&js_code=".$code."&grant_type=authorization_code";
        $apiData=file_get_contents($url);
        $apiData=json_decode($apiData,true);
        if ($apiData['errcode'] ==0){
            $data = MemberQy::where("userid",$apiData['userid'])->find();
            $get_user_url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&userid=".$apiData['userid']."&debug=1";
//            $get_user_url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=".$access_token."&department_id=1";
            $user_data = file_get_contents($get_user_url);
            $user_data = json_decode($user_data,true);
            if ($user_data['errcode'] != 0){
                return j(1,'获取用户信息失败',$user_data);
            }
            if (empty($data)){
                $data = new MemberQy();
                $data->corpid = $apiData['corpid'];
                $data->userid = $user_data['userid'];
                $data->session_key = $apiData['session_key'];
                $data->name = $user_data['name'];
                $data->mobile = $user_data['mobile'];
                $data->gender = $user_data['gender'];
                $data->gender = $user_data['gender'];
                $data->email = $user_data['email'];
                $data->avatar = $user_data['avatar'];
                $data->thumb_avatar = $user_data['thumb_avatar'];
                if (!$data->save()){
                    return j(1,'登录失败,添加用户信息错误');
                }
            }else{
                $data->session_key = $apiData['session_key'];
                $data->name = $user_data['name'];
                $data->avatar = $user_data['avatar'];
                $data->thumb_avatar = $user_data['thumb_avatar'];
                if (!$data->save()){
                    return j(1,'登录失败,添加用户信息错误');
                }
            }
            $encrypt = [
                'id' => $data->id,
                'userid' => $data['userid'],
            ];
            $userToken = AesFacade::encrypt(http_build_query($encrypt));
            return j(0,"登录成功",[
                'userToken'=>$userToken,
                'member' => $data
            ]);
        }
        return j(1,"登录失败,授权登录错误",$apiData);
    }
}

